import { t } from 'i18next'
import { useEffect, useState } from 'react'
import { Button } from '@kedacom/react-next'
import { StyleData, vmpStyleData } from '../interface'
import { StyledChoose } from './style'
import StyleModal from './StyleModal'

interface StyleChooseProps {
	styleData: StyleData
	scrollLength: number
	isShowSingle?: boolean
	disabled?: boolean
	onSelect: (id: number) => void
}

export default function StyleChoose(props: StyleChooseProps) {
	const { styleData, onSelect, isShowSingle, scrollLength, disabled } = props
	const [sliderIndex, setSliderIndex] = useState(0)
	const [open, setOpen] = useState<boolean>(false)
	useEffect(() => {
		setSliderIndex(Math.floor(vmpStyleData.findIndex((item) => item.id === styleData.id) / scrollLength))
	}, [styleData])
	const handlePrev = () => {
		!disabled &&
			setSliderIndex((state) => {
				return state <= 0 ? state : --state
			})
	}
	const handleNext = () => {
		!disabled &&
			setSliderIndex((state) => {
				return state >= Math.ceil(vmpStyleData.length / scrollLength) - 1 ? state : ++state
			})
	}
	return (
		<StyledChoose className="style-choose" disabled={disabled} width={70 * scrollLength}>
			{isShowSingle && (
				<div
					className={`single-box style-box select ${styleData.className}`}
					data-key={styleData.dataKey}
				></div>
			)}
			{!isShowSingle && (
				<>
					<div className="slider-bar">
						<div
							className={`slider-operate slider-operate-left ${disabled ? 'disabled' : ''}`}
							onClick={handlePrev}
						></div>
						<div className="slider-view">
							<ul style={{ transform: `translateX(${sliderIndex * -(70 * scrollLength)}px)` }}>
								{vmpStyleData.map((item) => (
									<li
										key={item.id}
										className={`style-box ${item?.className} ${
											item?.id === styleData.id ? 'select' : ''
										}`}
										data-key={item.dataKey}
										onClick={() => {
											!disabled && onSelect(item.id)
										}}
									></li>
								))}
							</ul>
						</div>
						<div
							className={`slider-operate slider-operate-right ${disabled ? 'disabled' : ''}`}
							onClick={handleNext}
						></div>
					</div>
					<Button
						disabled={disabled}
						onClick={() => {
							setOpen(true)
						}}
					>
						{t('全部')}
					</Button>
					<StyleModal open={open} style={styleData} setOpen={setOpen} onSelect={onSelect} />
				</>
			)}
		</StyledChoose>
	)
}
